<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class AppMiddleware
{
    public function handle($request, Closure $next)
    {
        
        if (!\Auth::guard('api')->check()) {
     
            return response()->json(['code' => 401, 'msg' => '用户未登录或已失效']);
        }
        $type = $request->header('ats');
        $type = $this->getDevice();
        $accessToken = \Auth::guard('api')->user()->token();
        $tokenId = $accessToken->id;
        $expire = strtotime($accessToken->expires_at);
        $time = time();
        $part  = $time-$expire;
        if($type){
            if($part<=0){
                DB::table('oauth_access_tokens')->where('id',$tokenId)->update(['expires_at'=>date('Y-m-d H:i:s',strtotime('+2 hours'))]);
            }else{
                return response()->json(['code' => 401, 'msg' => '用户未登录或已失效']);
            }
        }else{
            if($part<=0){
                DB::table('oauth_access_tokens')->where('id',$tokenId)->update(['expires_at'=>date('Y-m-d H:i:s',strtotime('+3 days'))]);
            }else{
                return response()->json(['code' => 401, 'msg' => '用户未登录或已失效']);
            }
        }
        return $next($request);
    }
    public function getDevice() {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (true == preg_match("/.+Windows.+/", $agent)) {
            return true;
        } elseif (true == preg_match("/.+Macintosh.+/", $agent)) {
            return true;
        } else {
            return false;
        }
    }
}
